<template>
  <div class="enterprise-ai-container">
    <!-- 顶部分析工具区域 -->
    <div class="top-section">
      <AnalysisToolsBar @tool-selected="handleSelectedTool" />
    </div>
    
    <!-- 主要聊天区域 -->
    <div class="main-section">
      <!-- 左侧聊天主题列表 -->
      <div class="left-panel">
        <ChatTopicList 
          :topics="chatTopics"
          :active-topic-id="activeTopic?.id"
          @topic-selected="selectTopic"
          @topic-created="createTopic"
          @topic-renamed="renameTopic"
          @topic-deleted="deleteTopic"
        />
      </div>
      
      <!-- 中间聊天区域 -->
      <div class="middle-panel">
        <div class="chat-header">
          <div class="topic-info">
            <h3>{{ activeTopic?.title || '新对话' }}</h3>
            <div class="model-info" v-if="activeModel">
              <span class="model-badge" :class="modelTypeClass">
                {{ modelTypeLabel }}
              </span>
              <span class="model-name">{{ activeModel.name }}</span>
            </div>
          </div>
          
          <div class="chat-actions">
            <el-tooltip content="清空对话" placement="top">
              <el-button 
                type="danger" 
                size="small" 
                plain 
                circle
                @click="confirmClearMessages"
                :disabled="!activeTopic || messages.length === 0"
              >
                <i class="fa fa-trash"></i>
              </el-button>
            </el-tooltip>
          </div>
        </div>
        
        <div class="chat-messages" ref="messagesContainer">
          <div class="empty-chat" v-if="messages.length === 0">
            <div class="empty-icon">
              <i class="fa fa-comments"></i>
            </div>
            <p>选择左侧对话主题或发送新消息开始对话</p>
          </div>
          
          <ChatMessageList 
            v-else
            :messages="messages" 
            :typing="isTyping"
            @preview-attachment="previewAttachment"
          />
        </div>
        
        <div class="chat-input-wrapper">
          <ChatInput 
            :loading="isTyping"
            :model-status="modelStatus"
            @send-message="sendMessage"
            @upload-attachment="uploadAttachment"
            ref="chatInput"
          />
        </div>
      </div>
      
      <!-- 右侧模型设置区域 -->
      <div class="right-panel">
        <ModelSettings 
          :active-model="activeModel"
          @model-changed="handleModelChanged"
        />
      </div>
    </div>
    
    <!-- 附件预览对话框 -->
    <el-dialog
      v-model="attachmentPreview.visible"
      :title="attachmentPreview.name"
      width="60%"
      destroy-on-close
    >
      <div class="attachment-preview-content">
        <img 
          v-if="attachmentPreview.type && attachmentPreview.type.startsWith('image/')" 
          :src="attachmentPreview.url" 
          :alt="attachmentPreview.name"
          class="attachment-preview-image"
        />
        <div v-else class="file-preview-placeholder">
          <i class="fa fa-file-text"></i>
          <p>{{ attachmentPreview.name }}</p>
          <p class="file-size">{{ formatFileSize(attachmentPreview.size) }}</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="attachmentPreview.visible = false">关闭</el-button>
          <el-button type="primary" @click="downloadAttachment">
            <i class="fa fa-download"></i> 下载
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStorage } from '@vueuse/core';
import DOMPurify from 'dompurify';

// 导入API接口
import { 
  getChatConversations, 
  createChatConversation, 
  updateChatConversation, 
  deleteChatConversation, 
  getChatMessages, 
  sendChatMessage,
  uploadChatAttachment,
  clearChatMessages
} from '/@/api/backend/yxerp/aichat';

// 导入组件
import AnalysisToolsBar from './components/enterprise/AnalysisToolsBar.vue';
import ChatTopicList from './components/enterprise/ChatTopicList.vue';
import ChatMessageList from './components/enterprise/ChatMessageList.vue';
import ChatInput from './components/enterprise/ChatInput.vue';
import ModelSettings from './components/enterprise/ModelSettings.vue';

// 状态管理
const activeModel = useStorage('yx-ai-active-model', null);
const activeTopic = ref(null);
const chatTopics = ref([]);
const messages = ref([]);
const isTyping = ref(false);
const chatInput = ref(null);
const messagesContainer = ref(null);
const userId = ref(1); // 临时固定用户ID，实际应从登录信息获取

// 附件预览相关
const attachmentPreview = ref({
  visible: false,
  url: '',
  name: '',
  type: '',
  size: 0,
  fileId: null
});

// 模型状态
const modelStatus = computed(() => {
  if (!activeModel.value) {
    return {
      connected: false,
      provider: '',
      model: ''
    };
  }
  
  return {
    connected: true,
    provider: activeModel.value.type === 'local' ? 'ollama' : activeModel.value.provider,
    model: activeModel.value.name
  };
});

// 模型类型样式和标签
const modelTypeClass = computed(() => {
  if (!activeModel.value) return '';
  
  if (activeModel.value.type === 'local') {
    return 'model-local';
  } else {
    switch (activeModel.value.provider) {
      case 'openai':
        return 'model-openai';
      case 'azure':
        return 'model-azure';
      case 'anthropic':
        return 'model-anthropic';
      case 'deepseek':
        return 'model-deepseek';
      default:
        return 'model-remote';
    }
  }
});

const modelTypeLabel = computed(() => {
  if (!activeModel.value) return '';
  
  if (activeModel.value.type === 'local') {
    return 'OLLAMA';
  } else {
    switch (activeModel.value.provider) {
      case 'openai':
        return 'OpenAI';
      case 'azure':
        return 'Azure';
      case 'anthropic':
        return 'Anthropic';
      case 'deepseek':
        return 'DeepSeek';
      default:
        return activeModel.value.provider ? activeModel.value.provider.toUpperCase() : '';
    }
  }
});

// 生命周期钩子
onMounted(async () => {
  // 加载聊天主题列表
  await loadChatTopics();
  
  // 如果有活动的主题ID，加载该主题
  if (activeTopic.value) {
    await loadMessages(activeTopic.value.id);
  }
  
  // 聚焦输入框
  chatInput.value?.focusInput();
});

// 加载聊天主题列表
async function loadChatTopics() {
  try {
    const response = await getChatConversations(userId.value);
    
    if (response.code === 1) {
      chatTopics.value = response.data;
      
      // 如果有主题，选择第一个
      if (chatTopics.value.length > 0 && !activeTopic.value) {
        selectTopic(chatTopics.value[0].id);
      }
    } else {
      ElMessage.error(response.msg || '加载聊天主题失败');
    }
  } catch (error) {
    console.error('加载聊天主题失败:', error);
    ElMessage.error('加载聊天主题失败');
  }
}

// 选择聊天主题
async function selectTopic(topicId) {
  if (activeTopic.value?.id === topicId) return;
  
  const topic = chatTopics.value.find(t => t.id === topicId);
  if (topic) {
    activeTopic.value = topic;
    
    // 加载主题消息
    await loadMessages(topicId);
    
    // 聚焦输入框
    chatInput.value?.focusInput();
  }
}

// 创建新聊天主题
async function createTopic(title) {
  if (!activeModel.value) {
    ElMessage.warning('请先在右侧面板选择或配置模型');
    return;
  }
  
  try {
    const modelId = activeModel.value.type === 'remote' ? activeModel.value.id : null;
    
    const response = await createChatConversation({
      user_id: userId.value,
      title: title || '新对话',
      model_id: modelId,
      model_type: activeModel.value.type,
      model_info: activeModel.value.type === 'local' ? JSON.stringify({
        name: activeModel.value.name,
        endpoint: activeModel.value.endpoint,
        params: activeModel.value.params
      }) : null
    });
    
    if (response.code === 1) {
      // 重新加载主题列表
      await loadChatTopics();
      
      // 选择新创建的主题
      selectTopic(response.data);
      
      return response.data;
    } else {
      ElMessage.error(response.msg || '创建聊天主题失败');
      return null;
    }
  } catch (error) {
    console.error('创建聊天主题失败:', error);
    ElMessage.error('创建聊天主题失败');
    return null;
  }
}

// 重命名聊天主题
async function renameTopic(topicId, newTitle) {
  try {
    const response = await updateChatConversation({
      id: topicId,
      title: newTitle
    });
    
    if (response.code === 1) {
      // 更新本地主题列表
      const index = chatTopics.value.findIndex(t => t.id === topicId);
      if (index !== -1) {
        chatTopics.value[index].title = newTitle;
        
        // 如果是当前活动主题，也更新标题
        if (activeTopic.value?.id === topicId) {
          activeTopic.value.title = newTitle;
        }
      }
      
      ElMessage.success('重命名成功');
    } else {
      ElMessage.error(response.msg || '重命名聊天主题失败');
    }
  } catch (error) {
    console.error('重命名聊天主题失败:', error);
    ElMessage.error('重命名聊天主题失败');
  }
}

// 删除聊天主题
async function deleteTopic(topicId) {
  try {
    const response = await deleteChatConversation(topicId);
    
    if (response.code === 1) {
      // 从本地主题列表中移除
      chatTopics.value = chatTopics.value.filter(t => t.id !== topicId);
      
      // 如果是当前活动主题，清空消息并将活动主题设为null
      if (activeTopic.value?.id === topicId) {
        activeTopic.value = null;
        messages.value = [];
      }
      
      // 如果还有其他主题，选择第一个
      if (chatTopics.value.length > 0 && !activeTopic.value) {
        selectTopic(chatTopics.value[0].id);
      }
      
      ElMessage.success('删除成功');
    } else {
      ElMessage.error(response.msg || '删除聊天主题失败');
    }
  } catch (error) {
    console.error('删除聊天主题失败:', error);
    ElMessage.error('删除聊天主题失败');
  }
}

// 加载主题消息
async function loadMessages(topicId) {
  try {
    const response = await getChatMessages(topicId);
    
    if (response.code === 1) {
      messages.value = response.data;
      
      // 滚动到底部
      await nextTick();
      scrollToBottom();
    } else {
      ElMessage.error(response.msg || '加载消息失败');
    }
  } catch (error) {
    console.error('加载消息失败:', error);
    ElMessage.error('加载消息失败');
  }
}

// 发送消息
async function sendMessage(message) {
  // 如果没有活动主题，创建一个新主题
  if (!activeTopic.value) {
    const topicId = await createTopic('新对话');
    if (!topicId) return;
  }
  
  // 添加用户消息到列表
  const userMessage = {
    id: Date.now(),
    role: 'user',
    content: message.content,
    web_search: message.web_search,
    attachments: message.attachments || [],
    temporary: true,
    created_at: new Date().toISOString()
  };
  
  messages.value.push(userMessage);
  
  // 滚动到底部
  await nextTick();
  scrollToBottom();
  
  // 显示AI正在输入
  isTyping.value = true;
  
  try {
    // 发送消息到服务器
    const response = await sendChatMessage({
      conversation_id: activeTopic.value.id,
      content: message.content,
      attachments: message.attachments,
      web_search: message.web_search
    });
    
    if (response.code === 1) {
      // 移除临时用户消息
      messages.value = messages.value.filter(m => !m.temporary);
      
      // 更新消息列表
      messages.value.push(...response.data);
      
      // 更新主题信息
      const topicIndex = chatTopics.value.findIndex(t => t.id === activeTopic.value.id);
      if (topicIndex !== -1) {
        chatTopics.value[topicIndex].last_message_time = new Date().toISOString();
        chatTopics.value[topicIndex].message_count = messages.value.length;
        
        // 将该主题移到列表顶部
        const topic = chatTopics.value.splice(topicIndex, 1)[0];
        chatTopics.value.unshift(topic);
      }
    } else {
      // 显示错误消息
      const errorMessage = {
        id: Date.now() + 1,
        role: 'ai',
        content: `处理消息时出错: ${response.msg || '未知错误'}`,
        error: true,
        created_at: new Date().toISOString()
      };
      
      messages.value.push(errorMessage);
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    
    // 显示错误消息
    const errorMessage = {
      id: Date.now() + 1,
      role: 'ai',
      content: `发送消息失败: ${error.message || '网络错误'}`,
      error: true,
      created_at: new Date().toISOString()
    };
    
    messages.value.push(errorMessage);
  } finally {
    isTyping.value = false;
    
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  }
}

// 上传附件
async function uploadAttachment(file) {
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('conversation_id', activeTopic.value?.id || 0);
    
    const response = await uploadChatAttachment(formData);
    
    if (response.code === 1) {
      return response.data;
    } else {
      ElMessage.error(response.msg || '上传附件失败');
      return null;
    }
  } catch (error) {
    console.error('上传附件失败:', error);
    ElMessage.error('上传附件失败');
    return null;
  }
}

// 预览附件
function previewAttachment(attachment) {
  attachmentPreview.value = {
    visible: true,
    url: attachment.url,
    name: attachment.filename,
    type: attachment.mime_type,
    size: attachment.size,
    fileId: attachment.id
  };
}

// 下载附件
function downloadAttachment() {
  if (attachmentPreview.value.url) {
    window.open(attachmentPreview.value.url, '_blank');
  }
}

// 确认清空消息
function confirmClearMessages() {
  ElMessageBox.confirm(
    '确定要清空当前对话的所有消息吗？此操作不可恢复。',
    '清空对话',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await clearChatMessages(activeTopic.value.id);
      
      if (response.code === 1) {
        // 清空消息列表
        messages.value = [];
        
        // 更新主题信息
        const topicIndex = chatTopics.value.findIndex(t => t.id === activeTopic.value.id);
        if (topicIndex !== -1) {
          chatTopics.value[topicIndex].message_count = 0;
        }
        
        ElMessage.success('已清空所有消息');
      } else {
        ElMessage.error(response.msg || '清空消息失败');
      }
    } catch (error) {
      console.error('清空消息失败:', error);
      ElMessage.error('清空消息失败');
    }
  }).catch(() => {});
}

// 处理使用分析工具
async function handleSelectedTool(tool) {
  // 检查是否有活动模型
  if (!activeModel.value) {
    ElMessage.warning('请先在右侧面板选择或配置模型');
    return;
  }
  
  // 构建提示词
  let prompt = `请使用${tool.name}分析工具:\n\n`;
  
  // 添加工具描述
  prompt += `工具描述: ${tool.description}\n\n`;
  
  prompt += `请提供详细的分析步骤、方法和建议。`;
  
  // 发送分析请求
  const message = {
    content: prompt,
    web_search: true,
    attachments: []
  };
  
  await sendMessage(message);
}

// 处理模型变更
function handleModelChanged(model) {
  activeModel.value = model;
  ElMessage.success(`已应用模型: ${model.name}`);
}

// 滚动到底部
function scrollToBottom() {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes) return '0 B';
  if (bytes < 1024) return bytes + ' B';
  else if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
  else if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
  else return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
}
</script>

<style scoped>
.enterprise-ai-container {
  display: flex;
  flex-direction: column;
  height: 95vh;
  overflow: hidden;
  background-color: #f8f9fa;
}

/* 顶部分析工具区域 */
.top-section {
  padding: 16px 20px;
  background: linear-gradient(135deg, #ffffff 0%, #f5f7fa 100%);
  border-radius: 12px;
  margin: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  flex-shrink: 0;
  max-height: 35vh;
  overflow: hidden;
}

/* 主要聊天区域 */
.main-section {
  flex: 1;
  display: flex;
  overflow: hidden;
  margin: 0 16px 16px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  min-height: 0; /* 确保flex子元素不会溢出 */
}

/* 左侧聊天主题列表 */
.left-panel {
  width: 16.666%;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: linear-gradient(180deg, #ffffff 0%, #f9fafc 100%);
  border-radius: 12px 0 0 12px;
}

/* 中间聊天区域 */
.middle-panel {
  width: 50%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 16px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(90deg, #f9fafc 0%, #f5f7fa 100%);
}

.topic-info h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  background: linear-gradient(90deg, #303133 0%, #606266 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.model-info {
  display: flex;
  align-items: center;
  margin-top: 4px;
  font-size: 12px;
  color: #606266;
}

.model-badge {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
  margin-right: 6px;
}

.model-local {
  background: linear-gradient(135deg, #f0f9eb 0%, #e1f3d8 100%);
  color: #67c23a;
}

.model-openai {
  background: linear-gradient(135deg, #ecf5ff 0%, #dbecff 100%);
  color: #409eff;
}

.model-azure {
  background: linear-gradient(135deg, #f0f3fa 0%, #e0e6f6 100%);
  color: #0078d4;
}

.model-anthropic {
  background: linear-gradient(135deg, #f6f3ff 0%, #ebe4ff 100%);
  color: #7b61ff;
}

.model-deepseek {
  background: linear-gradient(135deg, #f2f6fc 0%, #e2eaf9 100%);
  color: #175cff;
}

.model-remote {
  background: linear-gradient(135deg, #f0f2f5 0%, #e0e3e9 100%);
  color: #606266;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fb 100%);
  min-height: 0; /* 确保flex子元素不会溢出 */
}

.empty-chat {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #dcdfe6;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.chat-input-wrapper {
  padding: 16px;
  border-top: 1px solid #ebeef5;
  background: linear-gradient(180deg, #f9fafc 0%, #f5f7fa 100%);
}

/* 右侧模型设置区域 */
.right-panel {
  width: 33.334%;
  border-left: 1px solid #ebeef5;
  overflow: hidden;
  background: linear-gradient(180deg, #ffffff 0%, #f9fafc 100%);
  border-radius: 0 12px 12px 0;
}

/* 附件预览样式 */
.attachment-preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.attachment-preview-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.file-preview-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #606266;
}

.file-preview-placeholder i {
  font-size: 64px;
  margin-bottom: 16px;
  color: #909399;
  background: linear-gradient(135deg, #909399 0%, #606266 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.file-size {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 全局滚动条样式 */
:deep(*::-webkit-scrollbar) {
  width: 6px;
}

:deep(*::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(*::-webkit-scrollbar-thumb) {
  background: #dcdfe6;
  border-radius: 3px;
}

:deep(*::-webkit-scrollbar-thumb:hover) {
  background: #c0c4cc;
}
</style> 